const Router = require("@koa/router");
const router = new Router();
const { UserModel } = require("../db/index");
const {
  login,
  register,
  updateUserInfo,
  deleteUser,
  querySomeData
} = require('../controller/user')

router.get("/users", async (ctx, next) => {
  const data = await UserModel.findAll();
  ctx.body = {
    code: 200,
    msg: "success",
    data,
  };
});


router.post("/get", async (ctx) => {
  ctx.body = await querySomeData(ctx.request.body)
});

router.post("/login", async (ctx) => {
  const { username, password } = ctx.request.body;
  ctx.body = await login({
    username,
    password,
  })
});
router.post("/register", async (ctx) => {
  ctx.body = await register(ctx.request.body)
});
router.post("/addUser", async (ctx, next) => {
  try {
    const data = await UserModel.create(ctx.request.body);
    if (data != "" || null) {
      ctx.body = {
        code: 200,
        msg: "success",
        data
      };
    } else {
      ctx.body = {
        code: 200,
        msg: "error"
      };
    }
  } catch (error) {
    console.log(error.message)
    let msg = error.errors[0].message
    ctx.body = {
      code: 500,
      msg
    };
  }
});
// 改
router.post("/:id", async (ctx, next) => {
  ctx.body = await updateUserInfo(ctx.request.body, ctx.params.id)
});
// 删除
router.delete("/:id", async (ctx, next) => {
  ctx.body = await deleteUser(ctx.params.id)
});
module.exports = router;
